package com.eightywork.life.activity;

import cn.jpush.android.api.JPushInterface;

import com.eightywork.life.R;
import com.eightywork.life.service.DoService;
import com.eightywork.life.util.MyHttpException;
import com.umeng.analytics.MobclickAgent;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

public class PasswordFirstActivity extends BaseActivity implements OnClickListener {
	private EditText account;
	private ImageButton returnButton;
	private Button nextButton;
	private AsyncTask<?, ?, ?> task;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_password1);
		initView();
	}

	@Override
	protected void onDestroy() {
		if(task!=null){
			task.cancel(true);
		}
		super.onDestroy();
	}
	@Override
	public void onResume() {		
		super.onResume();
		JPushInterface.onResume(this);
	    MobclickAgent.onResume(this);
	}
	
	@Override
	public void onPause() {
	    super.onPause();
		JPushInterface.onPause(this);
	    MobclickAgent.onPause(this);
	}
	
	public void initView() {
		account = (EditText) findViewById(R.id.account);
		returnButton = (ImageButton) findViewById(R.id.button_left);
		nextButton = (Button) findViewById(R.id.button_next);
		returnButton.setOnClickListener(this);
		nextButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == returnButton) {
			finish();
		} else if (v == nextButton) {
			next();
		} 
	}

	private void next() {
		task = new NextTask().execute();
	}

	class NextTask extends AsyncTask<Void, String, String> {
		String username, uid;

		@Override
		protected void onPreExecute() {
			username = account.getEditableText().toString();
			showProgressDialog("请稍后...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				uid = DoService.lostpasswd1(username);
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result == null) {
				showAlert("申请成功", "操作验证码已经通过短信发送至您的手机中，请在5分钟内完成修改密码操作，否则操作失败！", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(context, PasswordSecondActivity.class);
						intent.putExtra("uid", uid);
						intent.putExtra("username", username);
						startActivity(intent);
						finish();
					}
				});
			} else {
				showMessage(result);
			}
			super.onPostExecute(result);
		}
	}
}
